package cn.iocoder.yudao.module.indicator.util.index;
 
/**
 * 题目：
 * 替换字符串中连续出现的指定字符串。
 *
 * 思路：
 * 把str中from部分所有位置的字符编码设置为0。
 *
 * @author Created by LiveEveryDay
 */
public class ReplaceConsecutiveSpecifiedString {
 
    public static String replace(String str, String from, String to) {
        if (str == null || from == null || str.equals("") || from.equals("")) {
            return str;
        }
        char[] arrStr = str.toCharArray();
        char[] arrFrom = from.toCharArray();
        int match = 0;
        for (int i = 0; i < arrStr.length; i++) {
            if (arrStr[i] == arrFrom[match++]) {
                if (match == arrFrom.length) {
                    clear(arrStr, i, arrFrom.length);
                    match = 0;
                }
            } else {
                match = 0;
            }
        }
        StringBuilder r = new StringBuilder();
        StringBuilder cur = new StringBuilder();
        for (int i = 0; i < arrStr.length; i++) {
            if (arrStr[i] != 0) {
                cur.append(arrStr[i]);
            }
            if (arrStr[i] == 0 && (i == 0 || arrStr[i - 1] != 0)) {
                r.append(cur).append(to);
                cur = new StringBuilder();
            }
        }
        if (!cur.toString().equals("")) {
            r.append(cur);
        }
        return r.toString();
    }
 
    private static void clear(char[] a, int end, int len) {
        while (len-- != 0) {
            a[end--] = 0;
        }
    }
 
    public static void main(String[] args) {
        String str = "{128}/{2}";
        String from = "{2}";
        String to = "96";
        System.out.printf("The result is: %s", replace(str, from, to));
    }
 
}
 
